﻿#region Old

//using System;
//using System.Linq;
//using System.Windows.Forms;
//using YougeBookmark.Business.Services;
//using YougeBookmark.DataAccess;
//using YougeBookmark.Models;

//namespace YougeBookmark.Forms
//{
//    public partial class BookmarkForm : Form
//    {
//        private readonly BookmarkService _bookmarkService;
//        private readonly TagService _tagService;
//        private readonly int? _existingBookmarkId;

//        public BookmarkForm(BookmarkService bookmarkService, TagService tagService, int? bookmarkId = null)
//        {
//            _bookmarkService = bookmarkService;
//            _tagService = tagService;
//            _existingBookmarkId = bookmarkId;

//            InitializeComponent();
//            InitializeFormData();
//        }

//        private void InitializeFormData()
//        {
//            // 加载所有标签
//            var tags = _tagService.GetAllTags().Item1;
//            clbTags.Items.Clear();
//            foreach (var tag in tags)
//            {
//                clbTags.Items.Add(tag, false);
//            }

//            // 如果是编辑模式，加载现有数据
//            if (_existingBookmarkId.HasValue)
//            {
//                var bookmark = _bookmarkService.GetBookmarkById(_existingBookmarkId.Value);
//                if (bookmark != null)
//                {
//                    txtUrl.Text = bookmark.Url;
//                    txtRemark.Text = bookmark.Remark;
//                    var selectedTagIds = bookmark.Tags.Split(',').Select(int.Parse).ToList();
//                    for (int i = 0; i < clbTags.Items.Count; i++)
//                    {
//                        var tag = (Tag)clbTags.Items[i];
//                        clbTags.SetItemChecked(i, selectedTagIds.Contains(tag.Id));
//                    }
//                }
//            }
//            else // 新建模式
//            {
//                // 尝试从剪贴板获取URL
//                if (Uri.TryCreate(Clipboard.GetText(), UriKind.Absolute, out var uri))
//                {
//                    txtUrl.Text = uri.ToString();
//                }
//            }
//        }

//        private void btnSave_Click(object sender, EventArgs e)
//        {
//            if (!ValidateInput()) return;

//            var selectedTags = clbTags.CheckedItems
//                .Cast<Tag>()
//                .Select(t => t.Id.ToString())
//                .ToList();

//            var bookmark = new Bookmark
//            {
//                Url = txtUrl.Text.Trim(),
//                Remark = txtRemark.Text,
//                Tags = string.Join(",", selectedTags),
//                CreatedAt = DateTime.Now
//            };

//            try
//            {
//                if (_existingBookmarkId.HasValue)
//                {
//                    bookmark.Id = _existingBookmarkId.Value;
//                    _bookmarkService.UpdateBookmark(bookmark);
//                }
//                else
//                {
//                    _bookmarkService.AddBookmark(bookmark);
//                }

//                DialogResult = DialogResult.OK;
//                Close();
//            }
//            catch (Exception ex)
//            {
//                MessageBox.Show($"保存失败：{ex.Message}", "错误",
//                    MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }
//        }

//        private bool ValidateInput()
//        {
//            if (string.IsNullOrWhiteSpace(txtUrl.Text))
//            {
//                MessageBox.Show("网址不能为空", "输入错误",
//                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
//                return false;
//            }

//            if (!Uri.TryCreate(txtUrl.Text, UriKind.Absolute, out _))
//            {
//                MessageBox.Show("请输入有效的网址", "输入错误",
//                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
//                return false;
//            }

//            return true;
//        }

//        private void btnCancel_Click(object sender, EventArgs e)
//        {
//            DialogResult = DialogResult.Cancel;
//            Close();
//        }
//    }
//}

#endregion Old

using System;
using System.Linq;
using System.Windows.Forms;
using YougeBookmark.Business.Services;
using YougeBookmark.DataAccess;
using YougeBookmark.Models;

namespace YougeBookmark.Forms
{
    public partial class BookmarkForm : Form
    {
        private readonly BookmarkService _bookmarkService; // 书签服务实例
        private readonly TagService _tagService;           // 标签服务实例
        private readonly int? _existingBookmarkId;        // 编辑模式下的书签ID

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="bookmarkService">书签服务</param>
        /// <param name="tagService">标签服务</param>
        /// <param name="bookmarkId">书签ID（编辑模式）</param>
        public BookmarkForm(BookmarkService bookmarkService, TagService tagService, int? bookmarkId = null)
        {
            _bookmarkService = bookmarkService;
            _tagService = tagService;
            _existingBookmarkId = bookmarkId;

            InitializeComponent();
            InitializeFormData();  // 初始化表单数据
        }

        /// <summary>
        /// 初始化表单数据
        /// </summary>
        private void InitializeFormData()
        {
            // 加载所有标签
            var tags = _tagService.GetAllTags().Item1;
            clbTags.Items.Clear();
            foreach (var tag in tags)
            {
                clbTags.Items.Add(tag, false);
            }

            // 如果是编辑模式，加载现有数据
            if (_existingBookmarkId.HasValue)
            {
                var bookmark = _bookmarkService.GetBookmarkById(_existingBookmarkId.Value);
                if (bookmark != null)
                {
                    txtUrl.Text = bookmark.Url;
                    txtRemark.Text = bookmark.Remark;
                    var selectedTagIds = bookmark.Tags.Split(',').Select(int.Parse).ToList();
                    for (int i = 0; i < clbTags.Items.Count; i++)
                    {
                        var tag = (Tag)clbTags.Items[i];
                        clbTags.SetItemChecked(i, selectedTagIds.Contains(tag.Id));
                    }
                }
            }
            else // 新建模式
            {
                // 尝试从剪贴板获取URL
                if (Uri.TryCreate(Clipboard.GetText(), UriKind.Absolute, out var uri))
                {
                    txtUrl.Text = uri.ToString();
                }
            }
        }

        /// <summary>
        /// 设置URL（用于从外部传入URL）
        /// </summary>
        /// <param name="url">网址</param>
        public void SetUrl(string url)
        {
            txtUrl.Text = url;
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateInput()) return;

            var selectedTags = clbTags.CheckedItems
                .Cast<Tag>()
                .Select(t => t.Id.ToString())
                .ToList();

            var bookmark = new Bookmark
            {
                Url = txtUrl.Text.Trim(),
                Remark = txtRemark.Text,
                Tags = string.Join(",", selectedTags),
                CreatedAt = DateTime.Now
            };

            try
            {
                if (_existingBookmarkId.HasValue)
                {
                    bookmark.Id = _existingBookmarkId.Value;
                    _bookmarkService.UpdateBookmark(bookmark);
                }
                else
                {
                    _bookmarkService.AddBookmark(bookmark);
                }

                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 验证输入数据
        /// </summary>
        /// <returns>是否验证通过</returns>
        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txtUrl.Text))
            {
                MessageBox.Show("网址不能为空", "输入错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (!Uri.TryCreate(txtUrl.Text, UriKind.Absolute, out _))
            {
                MessageBox.Show("请输入有效的网址", "输入错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// URL文本框内容改变事件
        /// </summary>
        private void txtUrl_TextChanged(object sender, EventArgs e)
        {
            var isValid = Uri.TryCreate(txtUrl.Text, UriKind.Absolute, out _);
            txtUrl.BackColor = isValid ? SystemColors.Window : Color.LavenderBlush;
        }

        /// <summary>
        /// 标签搜索框内容改变事件
        /// </summary>
        private void txtTagFilter_TextChanged(object sender, EventArgs e)
        {
            var keyword = txtTagFilter.Text.Trim();
            clbTags.BeginUpdate();
            clbTags.Items.Clear();
            foreach (var tag in _tagService.SearchTags(keyword))
            {
                clbTags.Items.Add(tag);
            }
            clbTags.EndUpdate();
        }
    }
}